package com.dong.nettyconcurrent.c03_chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.net.SocketAddress;
import java.util.HashMap;

public class MyChatServerHandler extends SimpleChannelInboundHandler<String> {

    private HashMap<String, Channel> map;

        private static ChannelGroup channelGroup =  new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println("服务器接受到"+ctx.channel().remoteAddress()+"的 消息:"+msg);
        Channel channel = ctx.channel();
        System.out.println("channelGroup.size(): --> "+channelGroup.size());
        for (Channel channel1 : channelGroup) {
            if(channel1==channel) {
                System.out.println("这个是我自己发的");
                channel1.writeAndFlush("[自己] : 发送消息: "+msg+"\n");
            }else {
                System.out.println("这个是我发给别人的");
                channel1.writeAndFlush(channel.remoteAddress()+"发送消息: "+msg+"\n");
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        ctx.close();
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        //super.channelRegistered(ctx);
        SocketAddress socketAddress = ctx.channel().remoteAddress();
        System.out.println("");
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        super.handlerAdded(ctx);
        channelGroup.writeAndFlush("[ 服务器 ]:  一个客户端加入 -> "+ ctx.channel().remoteAddress());
        channelGroup.add(ctx.channel());

    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        //
        //channelGroup.remove(ctx.channel());
        channelGroup.writeAndFlush("[ 服务器:  ] "+ctx.channel().remoteAddress()+" 离开");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
     //
        //   super.channelActive(ctx);
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress()+"  上线");

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //super.channelInactive(ctx);
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress()+"  下线");
    }
}
